/* -----------------
* brief
* 1. this is code gen by tools
* 2. for add/update/delete/query the data save in sql database
 */

package tenant

import (
	"errors"
	"github.com/go-xorm/xorm"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"saas_sys_base/redishelper"

	//"github.com/mjiulee/lego/utils"
)

const REDIS_TENAT_MEMBER_BY_ID_PREFIX string = "tenant_member_by_id:"
const REDIS_TENAT_MEMBER_BY_TID_UID_PREFIX string = "tenant_member_by_tid_and_uid:"
const REDIS_TENAT_MEMBER_BY_UID_ROLE_PREFIX string = "tenant_member_by_uid_and_role:"

func init() {
	//CheckRedisKey(REDIS_TENAT_BY_ID_PREFIX) //检查是否有重复key
	//CheckRedisKey(REDIS_TENAT_BY_WX_ID_PREFIX)
}

/*
实验性代码
*/
func (t *TenantMember) CacheUpdateAllBy(item *TenantMember) {
	if item.Id <= 0 {
		lego.LogError(errors.New("item.Id <= 0 in CacheUpdateAllBy"))
		return
	}
	_ = redishelper.RedisSetKeyEx(REDIS_TENAT_MEMBER_BY_ID_PREFIX+utils.Int64ToString(item.Id), item)
	_ = redishelper.RedisSetKeyEx(REDIS_TENAT_MEMBER_BY_TID_UID_PREFIX+lego.RedisIds(utils.Int64ToString(item.TenantId), utils.Int64ToString(item.Uid)), item)
	_ = redishelper.RedisSetKeyEx(REDIS_TENAT_MEMBER_BY_UID_ROLE_PREFIX+utils.Int64ToString(item.Uid) + lego.RedisIdAnd + string(item.Role), item)
}

func (t *TenantMember) CacheDelAllBy(item *TenantMember) {
	if item.Id <= 0 {
		lego.LogError(errors.New("item.Id <= 0 in CacheDelAllBy"))
		return
	}
	_ = redishelper.RedisDelKey(REDIS_TENAT_MEMBER_BY_ID_PREFIX+utils.Int64ToString(item.Id))
}

/* 根据id获取记录
 * -----------------
 */
func (t *TenantMember) RecodeById(id int64) *TenantMember {
	item := new(TenantMember)
	err := redishelper.RedisGetKeyEx(REDIS_TENAT_MEMBER_BY_ID_PREFIX+utils.Int64ToString(item.Id), item)
	if err == nil {
		return item
	}

	_, err = lego.GetDBEngine().ID(id).Where("if_del = ?", 0).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}

	t.CacheUpdateAllBy(item)

	return item
}

//查询租户及租户成员ID
func (t *TenantMember) RecodeByTidAndUid(tid int64, uid int64) *TenantMember {
	item := new(TenantMember)

	err := redishelper.RedisGetKeyEx(REDIS_TENAT_MEMBER_BY_TID_UID_PREFIX+lego.RedisIds(utils.Int64ToString(item.TenantId), utils.Int64ToString(item.Uid)), item)
	if err == nil {
		return item
	}
	_, err = lego.GetDBEngine().Where("if_del = ?", 0).
		And("uid = ?", uid).
		And("tenant_id = ?", tid).
		Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}

	t.CacheUpdateAllBy(item)

	return item
}

func (t *TenantMember) RecodeByUidAndRole(uid int64, role TENANT_ROLE) *TenantMember {
	item := new(TenantMember)
	item.Uid = uid
	item.Role = role
	//item.State = common.STATE_YES
	err := redishelper.RedisGetKeyEx(REDIS_TENAT_MEMBER_BY_UID_ROLE_PREFIX+utils.Int64ToString(item.Uid) + lego.RedisIdAnd + string(item.Role), item)
	if err == nil {
		return item
	}

	_, err = lego.GetDBEngine().Where("if_del = ?", 0).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}

	t.CacheUpdateAllBy(item)

	return item
}

/* 添加
 * -----------------
 */
func (t *TenantMember) AddRecode(item2add *TenantMember) bool {
	item2add.Id = lego.UUID()
	_, err := lego.GetDBEngine().Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

func (t *TenantMember) AddRecodeWithsession(session *xorm.Session, item2add *TenantMember) bool {
	item2add.Id = lego.UUID()
	_, err := session.Insert(item2add)
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 删除(硬删除)*/
func (t *TenantMember) DelRecodeById(id int64) bool {
	item := new(TenantMember)
	_, err := lego.GetDBEngine().ID(id).Delete(item)
	if err != nil {
		lego.LogError(err)
		return false
	}

	itemDel := new(TenantMember)
	_ = redishelper.RedisGetKeyEx(REDIS_TENAT_MEMBER_BY_ID_PREFIX+utils.Int64ToString(id), itemDel)
	t.CacheDelAllBy(item)

	return true
}

func (t *TenantMember) DelRecodeByIdWithSession(session *xorm.Session, id int64) bool {
	item := new(TenantMember)
	_, err := session.ID(id).Delete(item)
	if err != nil {
		lego.LogError(err)
		return false
	}

	itemDel := new(TenantMember)
	_ = redishelper.RedisGetKeyEx(REDIS_TENAT_MEMBER_BY_ID_PREFIX+utils.Int64ToString(id), itemDel)
	t.CacheDelAllBy(item)

	return true
}

/* 更新
 * -----------------*/
func (t *TenantMember) UpdateRecode(rc *TenantMember) bool {
	_, err := lego.GetDBEngine().Id(rc.Id).Update(rc)
	if err != nil {
		lego.LogError(err)
		return false
	}

	t.CacheDelAllBy(rc)

	return true
}

func (t *TenantMember) UpdateRecodeWithSession(session *xorm.Session, rc *TenantMember) bool {
	_, err := session.ID(rc.Id).Update(rc)
	if err != nil {
		lego.LogError(err)
		return false
	}

	t.CacheDelAllBy(rc)

	return true
}


func (t *TenantMember) ListTenantByMemberUid(uid int64) ([]*Tenant, int64, error) {
	//start := (page*psize)
	resultList := make([]*Tenant, 0)

	session := lego.GetDBEngine().Table("tb_tenant_member").Alias("t1").
		Join("INNER", []string{"tb_tenant", "t2"}, "t1.tenant_id = t2.id").
		//Join("INNER", "tb_xx", "tb_xx.id = tb_xx.type_id").
		Where("t1.if_del = ? And t2.if_del = ?", 0, 0).
		And("t1.uid = ?", uid)
		//Limit(psize, start).
		//Desc("t1.field_xxx").
		//Asc()
	//OrderBy("asc")

	session2 := *session.Clone()
	err := session.Find(&resultList)
	if err != nil {
		return nil, 0, err
	}

	total, err := session2.Count()
	if err != nil {
		return nil, 0, err
	}
	return resultList, total, err
}
